﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using GalaSoft.MvvmLight.Ioc;
using Tisbi.LawFirm.BL;
using Tisbi.LawFirm.BL.Services;
using Tisbi.LawFirm.DAL.Models;
using Tisbi.LawFirm.UI.Views.Controls.Forms;

namespace Tisbi.LawFirm.UI.ViewModel
{
    public class LawsuitsViewModel : BaseViewModel<Lawsuits, ILawsuitsServiceAgent>
    {
        public int CaseId { get; set; }

        private ObservableCollection<Court> _courts;
        public ObservableCollection<Court> Courts
        {
            get { return _courts; }
            set
            {
                _courts = value;
                RaisePropertyChanged(() => Courts);
            }
        }
        private ObservableCollection<StatementOfClaimType> _statementOfClaimTypes;
        public ObservableCollection<StatementOfClaimType> StatementOfClaimTypes
        {
            get { return _statementOfClaimTypes; }
            set
            {
                _statementOfClaimTypes = value;
                RaisePropertyChanged(() => Courts);
            }
        }

        private ObservableCollection<CourtType> _courtTypes;
        public ObservableCollection<CourtType> CourtTypes
        {
            get { return _courtTypes; }
            set
            {
                _courtTypes = value;
                RaisePropertyChanged(() => CourtTypes);
            }
        }

        private ObservableCollection<District> _districts;
        public ObservableCollection<District> Districts
        {
            get { return _districts; }
            set
            {
                _districts = value;
                RaisePropertyChanged(() => Districts);
            }
        }

        private ObservableCollection<Customers> _customers;
        public ObservableCollection<Customers> Customers
        {
            get { return _customers; }
            set
            {
                _customers = value;
                RaisePropertyChanged(() => Customers);
            }
        }

        protected override void LoadModelBySearch()
        {
            IsBusy = true;

            ModelServiceAgent.GetItemByCases
                (
                    CaseId,
                    (list, exception) =>
                        ModelLoadedByWhere(list, exception, item => item.Number.Contains(SearchCriteria))
                );
        }

        protected override void LoadModel()
        {
            // Flip busy flag
            IsBusy = true;

            // Load items
            ModelServiceAgent.GetItemByCases
                (
                    CaseId,
                    ModelLoaded
                );
        }

        protected override void ShowEditDialog()
        {
            if (SelectedModelItem == null)
            {
                return;
            }

            LoadData();

            DetailModel = new LawsuitCRUDViewModal(SelectedModelItem)
            {
                LocationCaseMaterials = Courts,
                Courts = Courts,
                CourtTypes = CourtTypes,
                Districts = Districts,
                Plaintiffs = Customers,
                Defendants = Customers,
                ThirdParties = Customers
            };

            var appealsViewModel = SimpleIoc.Default.GetInstance<AppealsViewModel>();
            if (appealsViewModel != null)
            {
                appealsViewModel.ReloadModel(SelectedModelItem.Id);
            }

            ShowEditDialog<LawsuitCRUDForm>(DetailModel, "Карточка изменения иска", minWidth: 900, minHeight: 760);
        }

        protected override void ShowCreatedDialog()
        {
            LoadData();

            var newItem = new Lawsuits { Created = DateTime.Now };
            DetailModel = new LawsuitCRUDViewModal(newItem)
            {
                StatementOfClaimTypes = StatementOfClaimTypes,
                LocationCaseMaterials = Courts,
                Courts = Courts,
                CourtTypes = CourtTypes,
                Districts = Districts,
                Plaintiffs = Customers,
                Defendants = Customers,
                ThirdParties = Customers
            };

            var appealsViewModel = SimpleIoc.Default.GetInstance<AppealsViewModel>();
            if (appealsViewModel != null)
            {
                appealsViewModel.ReloadModel(0);
            }

            ShowCreatedDialog<LawsuitCRUDForm>(DetailModel, "Карточка создания нового иска", minWidth: 900, minHeight: 760);
        }

        protected override void OnSelectedModelItemSelect()
        {
            if (IsInDesignModeStatic)
            {
                return;
            }

            var appealsViewModel = SimpleIoc.Default.GetInstance<AppealsViewModel>();
            if (appealsViewModel == null || SelectedModelItem == null)
            {
                return;
            }

            appealsViewModel.ReloadModel(SelectedModelItem.Id);
        }

        protected override void Edit(Lawsuits editItem)
        {
            base.Edit(editItem);
            var caseViewModel = SimpleIoc.Default.GetInstance<CaseViewModel>();
            caseViewModel.LoadMeetings();
        }

        protected override void Add(Lawsuits newItem)
        {
            if (newItem != null)
            {
                ModelServiceAgent.AddItem(newItem, ItemsSaved);

                var caseViewModel = SimpleIoc.Default.GetInstance<CaseViewModel>();
                Cases cases = caseViewModel.SelectedModelItem;
                if (cases.Lawsuitses == null)
                {
                    cases.Lawsuitses = new List<Lawsuits>();
                }
                cases.Lawsuitses.Add(newItem);

                CaseServiceAgent.Edit(cases, delegate(Exception error)
                {
                    if (error != null)
                    {
                        Notifyer.NotifyError("Unable to save items", error);
                    }
                });

                LoadModel();
                caseViewModel.LoadMeetings();
            }

            if (PopUpDialog != null)
            {
                PopUpDialog.Close();
            }
        }

        private void LoadData()
        {
            // Flip busy flag
            IsBusy = true;

            // Load items
            CourtTypesServiceAgent.GetItem
                (
                    CourtTypesLoaded
                );
            DistrictsServiceAgent.GetItem
                (
                    DistrictsLoaded
                );
            CustomersServiceAgent.GetItem
                (
                    CustomersLoaded
                );
            CourtServiceAgent.GetItem
                (
                    CourtsLoaded
                );
            StatementOfClaimTypeServiceAgent.GetItem
                (
                    StatementOfClaimTypeLoaded
                );
        }

        private void StatementOfClaimTypeLoaded(List<StatementOfClaimType> entities, Exception error)
        {
            // If no error is returned, set the model to entities
            if (error == null)
            {
                StatementOfClaimTypes = new ObservableCollection<StatementOfClaimType>(entities);
            }
            // Otherwise notify view that there's an error
            else
            {
                Notifyer.NotifyError("Unable to retrieve items", error);
            }

            // Set SelectedItem to the first item
            if (StatementOfClaimTypes == null || StatementOfClaimTypes.Count <= 0)
            {
                HasVarnings = true;

                if (!string.IsNullOrWhiteSpace(Varnings))
                {
                    Varnings += "\n";
                }
                Varnings += "В базе отсудствуют виды исков, для продолжения работы добавьте в реестр новый [url=/Views/Pages/StatementOfClaim.xaml|_top]вид иска[/url].";
            }

            // We're done
            IsBusy = false;

            SetCanProperties();
        }
        private void CustomersLoaded(List<Customers> entities, Exception error)
        {
            // If no error is returned, set the model to entities
            if (error == null)
            {
                Customers = new ObservableCollection<Customers>(entities);
            }
            // Otherwise notify view that there's an error
            else
            {
                Notifyer.NotifyError("Unable to retrieve items", error);
            }

            // Set SelectedItem to the first item
            if (Customers == null || Customers.Count <= 0)
            {
                HasVarnings = true;

                if (!string.IsNullOrWhiteSpace(Varnings))
                {
                    Varnings += "\n";
                }
                Varnings += "В базе отсудствуют клиенты, для продолжения работы добавьте в реестр нового [url=/Views/Pages/Customers.xaml|_top]клиента[/url].";
            }

            // We're done
            IsBusy = false;

            SetCanProperties();
        }
        private void DistrictsLoaded(List<District> entities, Exception error)
        {
            // If no error is returned, set the model to entities
            if (error == null)
            {
                Districts = new ObservableCollection<District>(entities);
            }
            // Otherwise notify view that there's an error
            else
            {
                Notifyer.NotifyError("Unable to retrieve items", error);
            }

            // Set SelectedItem to the first item
            if (Districts == null || Districts.Count <= 0)
            {
                HasVarnings = true;

                if (!string.IsNullOrWhiteSpace(Varnings))
                {
                    Varnings += "\n";
                }
                Varnings += "В базе отсудствуют федеральные округи, для продолжения работы добавьте в реестр новый [url=/Views/Pages/Districts.xaml|_top]федеральный округ[/url].";
            }

            // We're done
            IsBusy = false;

            SetCanProperties();
        }
        private void CourtTypesLoaded(List<CourtType> entities, Exception error)
        {
            // If no error is returned, set the model to entities
            if (error == null)
            {
                CourtTypes = new ObservableCollection<CourtType>(entities);
            }
            // Otherwise notify view that there's an error
            else
            {
                Notifyer.NotifyError("Unable to retrieve items", error);
            }

            // Set SelectedItem to the first item
            if (CourtTypes == null || CourtTypes.Count <= 0)
            {
                HasVarnings = true;

                if (!string.IsNullOrWhiteSpace(Varnings))
                {
                    Varnings += "\n";
                }
                Varnings += "В базе отсудствуют типы судов, для продолжения работы добавьте в реестр новый [url=/Views/Pages/CourtTypes.xaml|_top]тип суда[/url].";
            }

            // We're done
            IsBusy = false;

            SetCanProperties();
        }
        private void CourtsLoaded(List<Court> entities, Exception error)
        {
            // If no error is returned, set the model to entities
            if (error == null)
            {
                Courts = new ObservableCollection<Court>(entities);
            }
            // Otherwise notify view that there's an error
            else
            {
                Notifyer.NotifyError("Unable to retrieve items", error);
            }

            // Set SelectedItem to the first item
            if (Courts == null || Courts.Count <= 0)
            {
                HasVarnings = true;

                if (!string.IsNullOrWhiteSpace(Varnings))
                {
                    Varnings += "\n";
                }
                Varnings += "В базе отсудствуют суды, для продолжения работы добавьте в реестр новый [url=/Views/Pages/Courts.xaml|_top]суд[/url].";
            }

            // We're done
            IsBusy = false;

            SetCanProperties();
        }

        public void ReloadModel(int casesId)
        {
            CaseId = casesId;
            LoadModel();
        }
    }
}
